package fragment.recommendfragments;


import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.lanou.horo.myapplication.R;
import com.lanou.horo.myapplication.dbdao.FristDbEntity;

import java.util.ArrayList;
import java.util.List;

import dbdao.FristDBHelper;
import dbdao.FristTopDBHelper;
import entity.RecommendedPageEntity;
import fragment.AbsBaseFragment;
import tools.IsInternet;
import tools.ItemOnClickListenerOther;
import utils.viewtools.SpacesItemDecoration;

import utils.adapter.RecomendTopDBViewPagerAdpter;
import utils.adapter.RecomenddbAdpter;
import utils.adapter.RecommendViewPagerAdpter;
import utils.adapter.RecommendedPageAdapter;
import utils.texttools.StringUtil;
import volley.VolleySingleton;


/**
 * 推荐 fragment
 * Created by dllo on 15/11/17.
 */
public class RecommendedPageFragment extends AbsBaseFragment implements ItemOnClickListenerOther {

    private RecommendedPageAdapter adapter;
    private String URL = "http://mobile.ximalaya.com/mobile/discovery/v1/recommends?channel=an" +
            "d-a1&device=android&includeActivity=true&includeSpecial=true&scale=2&version=4.3" +
            ".26.2";

    private RecyclerView recyclerView;
    private ViewPager viewPager;
    private RecommendViewPagerAdpter pageAdapter;

    private RecomendTopDBViewPagerAdpter topDBViewPagerAdpter;


    private int maxItem;

    private int currentItem;
    Handler handler;
    private RecyclerViewHeader viewHeader;
    private FristDBHelper helper;
    private RecomenddbAdpter dbadpter;
    private FristTopDBHelper topHelper;

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_page_recommended;
    }
//
    private Runnable r = new Runnable() {
        @Override
        public void run() {
            currentItem++;
            maxItem = pageAdapter.getCount();
            if (maxItem != 0)
            viewPager.setCurrentItem(currentItem % maxItem);
            handler.postDelayed(r, 3000);

        }
    };


    @Override
    protected void initView() {

        recyclerView = findView(R.id.recommeRecylerView);
        viewPager = findView(R.id.recommend_viewPager);
        viewHeader = findView(R.id.recommend_heard);
        helper = FristDBHelper.getInstance();
        topHelper = FristTopDBHelper.getInstance();


    }


    @Override
    protected void initData() {

        //设置轮播图
        handler = new Handler();

        GridLayoutManager manager = new GridLayoutManager(getContext(), 1);
        manager.setOrientation(LinearLayout.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(true);
        //有网的时候进行网络请求
        if (IsInternet.isNetworkAvailable(getContext())) {
            adapter = new RecommendedPageAdapter(getContext());
            adapter.setItem(this);
            recyclerView.setAdapter(adapter);

            pageAdapter = new RecommendViewPagerAdpter(getFragmentManager());
            viewPager.setAdapter(pageAdapter);


            Log.d("RecommendedPageFragment", "第一个========");
            initNetwork();
        }
        //没有网络的时候从数据库中取数据
        else {
            Toast.makeText(getContext(), "网络连接有问题" + helper.queryAll(), Toast.LENGTH_SHORT).show();
            dbadpter = new RecomenddbAdpter(getContext());
            recyclerView.setAdapter(dbadpter);
            topDBViewPagerAdpter = new RecomendTopDBViewPagerAdpter(getFragmentManager());
            viewPager.setAdapter(topDBViewPagerAdpter);
            topDBViewPagerAdpter.addImages(topHelper.queryAll());
            dbadpter.addDB(helper.queryAll());
        }
        viewHeader.attachTo(recyclerView, true);
        recyclerView.addItemDecoration(new SpacesItemDecoration(10));
    }


    @Override
    public void itemListener(Object o, int i) {

        long id;
        String tit;
        int position;
        String titlt;

        RecommendedPageEntity.HotRecommendsEntity.ListEntity en =
                (RecommendedPageEntity.HotRecommendsEntity.ListEntity) o;

        switch (i) {
            case 0:
                id = en.getList().get(0).getAlbumId();
                tit = en.getList().get(0).getTitle();
                position = 1;
                titlt = StringUtil.utf8Encode(tit);
                goToNext(new ReCommendDetailsFragment(id, position));
                List<FristDbEntity> datas = new ArrayList<>();
                FristDbEntity entity = new FristDbEntity();
                entity.setRdItemContentImgF(en.getList().get(0).getCoverLarge());
                entity.setRecommendedItemContentF(en.getList().get(0).getTitle());
                entity.setRdItemContentImgS(en.getList().get(1).getCoverLarge());
                entity.setRecommendedItemContentS(en.getList().get(1).getTitle());
                entity.setRdItemContentImgT(en.getList().get(2).getCoverLarge());
                entity.setRecommendedItemContentT(en.getList().get(2).getTitle());
                datas.add(entity);
                helper.saveHost(datas);


                break;
            case 1:
                id = en.getList().get(1).getAlbumId();
                tit = en.getList().get(1).getTitle();
                position = 2;
                titlt = StringUtil.utf8Encode(tit);
                goToNext(new ReCommendDetailsFragment(id, position));


                break;
            case 2:
                id = en.getList().get(2).getAlbumId();
                tit = en.getList().get(2).getTitle();
                position = 3;
                titlt = StringUtil.utf8Encode(tit);
                goToNext(new ReCommendDetailsFragment(id, position));
                break;

        }

    }
//     public  void saveDatadb(){
//
//    }

    private void initNetwork() {
        VolleySingleton.getInstance().addRequest(URL,
                RecommendedPageEntity.class, new Response.Listener<RecommendedPageEntity>() {
                    @Override
                    public void onResponse(RecommendedPageEntity response) {
                        if (response != null) {
                            RecommendedPageEntity.HotRecommendsEntity result = response.getHotRecommends();
                            if (result != null) {
                                List<RecommendedPageEntity.HotRecommendsEntity.ListEntity> list = result.getList();
                                if (list != null) {
                                    adapter.addRHList(list);
                                }

                            }
                            RecommendedPageEntity.FocusImagesEntity images = response.getFocusImages();
                            if (images != null) {
                                List<RecommendedPageEntity.FocusImagesEntity.ListEntity> image = images.getList();
                                if (image != null) {
                                    pageAdapter.addImages(image);
                                    handler.postDelayed(r, 3000);
                                    // Log.d("RecommendedPageFragment", "image:" + image);

                                }
                            }

                            dismissDialog();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        dismissDialog();
                        toastError();
                    }
                });
        showDialog();

    }


}